#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/07/21
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from flask import Blueprint, render_template, redirect, url_for, request, json, session
from flask_login import login_required, current_user
from project.define import admin_required, conn_logger
from .page import Messager


# 运行日志
logs = Blueprint(name='logs', import_name='project', url_prefix='/logs', template_folder='routes/logs/html')
# 页面消息管理器
PageMessager = Messager()


@logs.route('/')
@login_required
@admin_required
def default():
    """
    重定向
    """
    return redirect(url_for('logs.carpark'))


@logs.route('/carpark',methods=['POST', 'GET'])
@login_required
@admin_required
def carpark():
    """
    运行日志
    """
    page = int(request.args.get('page', 1))
    if request.method == 'POST':
        try:
            # 检查数据类型
            p_data = request.get_json()
            if not isinstance(p_data, dict):
                p_data = json.loads(p_data)
            p_data['View'] = 'logs'
            for k, v in p_data.items():
                if k == "SetFilter":
                    session['CarParkLog'] = v
            conn_logger.debug(f"用户：{current_user.LoginName } 接口：manager.logs 数据：{p_data}")
            return "OK"
        except Exception as e:
            conn_logger.error(f"用户：{current_user.LoginName } 接口：manager.logs 数据：{p_data} 错误：{e}")
        return PageMessager.error('处理错误，请联系管理员')
    return render_template('logs_carpark.html', **PageMessager.carpark_logs_data(page))


@logs.route('/camera',methods=['POST', 'GET'])
@login_required
@admin_required
def camera():
    """
    运行日志
    """
    page = int(request.args.get('page', 1))
    if request.method == 'POST':
        try:
            # 检查数据类型
            p_data = request.get_json()
            if not isinstance(p_data, dict):
                p_data = json.loads(p_data)
            p_data['View'] = 'logs'
            for k, v in p_data.items():
                if k == "SetFilter":
                    session['CameraLog'] = v
            conn_logger.debug(f"用户：{current_user.LoginName } 接口：manager.logs 数据：{p_data}")
            return "OK"
        except Exception as e:
            conn_logger.error(f"用户：{current_user.LoginName } 接口：manager.logs 数据：{p_data} 错误：{e}")
        return PageMessager.error('处理错误，请联系管理员')
    return render_template('logs_camera.html', **PageMessager.camera_logs_data(page))
    